// pages/homework/login/login.js
import http from '../../../utils/request.js'
import https from '../../../utils/request2.js'
import httpLogin from '../../../utils/request3.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    attention: '',
    studentNum: '',
    studentName: '',
    role: 1,
    userName: '',
    passWord: '',
    showBindDialog: false,
    bindRoles: [],
    useAutoLogin: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  // dyxx(){
  //   wx.requestSubscribeMessage({
  //     tmplIds: ['6ICTDEA6K_bPnQoS3fPNvywB9I2zSeT7ZPLW4uBAw-g'], // 最多3个模板ID
  //     success(res) {
  //       // 处理用户授权结果（accept/reject）
  //       console.log(res);
  //     }
  //   });
  // },
  getUserProfile() {
    wx.getUserInfo({
      desc: '用于完善用户资料',
      success: function (res) {
        // const encryptedData = res.encryptedData;
        // const iv = res.iv;
        console.info('res', res)
        // 将 encryptedData、iv 和 session_key 等信息发送到服务器进行解密
      },
      fail: function (err) {
        console.log('获取用户信息失败', err);
      }
    });
  },
  selectRole(e) {
    this.setData({
      role: e.currentTarget.dataset.index,
      studentNum: null,
      studentName: null,
      userName: null,
      passWord: null,
      attention: '',
      isFormValid: false
    })
  },
  // async onLoad(options) { 

  //     wx.login({
  //       success: async (res) => {
  //           if (res.code) {
  //             // const code = res.code; // 临时登录凭证
  //             console.info(res.code)
  //             const response = await https({
  //               url: '/open/system/getJscode2session',
  //               method: 'get',
  //               data: { code: res.code },
  //               header: { "content-type": "application/json" }
  //             });
  //             if(response.data.code==200){
  //               wx.setStorageSync('wxopenid',response.data.msg)
  //               let obj={
  //                 openId:JSON.parse(response.data.msg).openid
  //               }
  //               let that = this
  //                 let data = {
  //                   url:'/open/system/getStatusByOpenId',
  //                   method:'get',
  //                   data:obj,
  //                   header:{"content-type":"application/json;charset=UTF-8"}
  //               }
  //               let ress = await https(data)  // Now this await is valid
  //               if(ress&&ress.data.code==200){
  //                 if(ress.data.data!=null){
  //                   let that = this
  //                   let loginoptions={
  //                       url:'/student/login',
  //                       method:'get',
  //                       data:{studentNum:ress.data.data.studentNum,studentName:ress.data.data.studentName},
  //                       header:{"content-type":"application/json;charset=UTF-8"}
  //                   }
  //                   let reslogin = await http(loginoptions)
  //                   if(reslogin &&reslogin .data.code==200){
  //                       this.setData({
  //                           studentNum: null,
  //                           studentName: null
  //                       })
  //                       let token = JSON.stringify(reslogin.data.data)
  //                       wx.setStorageSync('studentToken',token)
  //                       // getApp().globalData.needRefresh = true;
  //                       wx.switchTab({
  //                         url: '/pages/homework/selecthomework/selecthomework',
  //                       });
  //                   }else{
  //                       this.setData({attention:reslogin.data.message})
  //                   }
  //                   // let token = JSON.stringify(ress.data.data)
  //                   // wx.setStorageSync('studentToken',token)

  //                 }
  //               }
  //             } else {
  //                 wx.showToast({
  //                     title: response.data.message,
  //                     icon: 'none',
  //                     duration: 2000 //持续的时间
  //                 })
  //             }
  //           } else {
  //             console.error('wx.login 失败:', res.errMsg);
  //           }
  //         }
  //     });

  // },
  async onLoad(options) {
    if (!this.data.useAutoLogin) {
      console.log('用户选择手动登录，不自动登录');
      return;
    }
    wx.login({
      success: async (res) => {
        if (res.code) {
          const response = await https({
            url: '/open/system/getJscode2session',
            method: 'get',
            data: { code: res.code },
          });
          if (response.data.code == 200) {
            wx.setStorageSync('wxopenid', response.data.msg);
            let openId = JSON.parse(response.data.msg).openid;

            let ress = await https({
              url: '/open/system/getStatusByOpenId',
              method: 'get',
              data: { openId },
            });

            if (ress && ress.data.code == 200 && ress.data.data) {
              let teacherItem = ress.data.data.itemList.find(item => item.roleType === 2);
              if (teacherItem && teacherItem.token) {
                wx.setStorageSync('teacherToken', teacherItem.token);
                wx.setStorageSync('username', teacherItem.number);
                wx.setStorageSync('hasShownBindPrompt', false);
                // console.log('教师token已保存:', teacherItem.token);
              }

              let list = ress.data.data.itemList.map(item => {
                return {
                  roleType: item.roleType === 2 ? 'teacher' : 'student',
                  studentName: item.name,
                  studentNum: item.number,
                  phoneNumber: item.number,
                }
              })
              this.setData({ bindRoles: list, showBindDialog: true });

            } else {
              // wx.showModal({
              //   title: '提示',
              //   content: '检测到您未绑定账号，请先绑定或用账号密码登录',
              //   showCancel: false
              // })
              console.log("检测到您未绑定账号，请先绑定或用账号密码登录");

            }
          } else {
            wx.showToast({ title: response.data.message, icon: 'none' })
          }
        } else {
          console.error('wx.login 失败:', res.errMsg);
        }
      }
    });
  },
  // async bindLogin(e) {
  //   const index = e.currentTarget.dataset.index;
  //   const role = this.data.bindRoles[index];

  //   // 统一调用登录接口，角色不同传不同参数
  //   let loginData = {};
  //   if (role.roleType === 'student') {
  //     loginData = { studentNum: role.studentNum, studentName: role.studentName };
  //   } else if (role.roleType === 'teacher') {
  //     loginData = { teacherId: role.teacherId, teacherName: role.teacherName };
  //   }

  //   let reslogin = await http({
  //     url: '/student/login', 
  //     method: 'get',
  //     data: loginData,
  //   });

  //   if (reslogin && reslogin.data.code === 200) {
  //     let token = JSON.stringify(reslogin.data.data);
  //     let studentUserInfo = reslogin.data.data
  //     wx.setStorageSync('studentUserInfo', studentUserInfo);
  //     wx.setStorageSync('studentToken', token);
  //     wx.switchTab({ url: '/pages/homework/selecthomework/selecthomework' });
  //   } else {
  //     wx.showToast({ title: reslogin.data.message, icon: 'none' });
  //   }
  // },
  async bindLogin(e) {
    try {
      const index = e.currentTarget.dataset.index;
      const role = this.data.bindRoles[index];

      if (role.roleType === 'student') {
        // 学生登录
        let loginData = {
          studentNum: role.studentNum,
          studentName: role.studentName
        };
        console.log(loginData, "检测");

        let reslogin = await http({
          url: '/student/login',
          method: 'get',
          data: loginData,
          header: { "content-type": "application/json;charset=UTF-8" }
        });

        if (reslogin && reslogin.data.code === 200) {
          let role = "student"
          wx.setStorageSync('role', role)
          let token = JSON.stringify(reslogin.data.data);
          wx.setStorageSync('studentToken', token);
          wx.setStorageSync('studentUserInfo', reslogin.data.data);
          wx.setStorageSync('hasShownBindPrompt', false);
          wx.switchTab({ url: '/pages/homework/selecthomework/selecthomework' });
        } else {
          wx.showToast({ title: reslogin.data.message, icon: 'none' });
        }

      } else if (role.roleType === 'teacher') {
        let Username = role.studentNum
        let options = {
          url: '/loginMiniTeacher',
          method: 'post',
          data: { username: role.studentNum },
          header: { "content-type": "application/json;charset=UTF-8" }
        }
        let res = await httpLogin(options)
        if (res && res.data.code == 200) {
          let role = "teacher"
          wx.setStorageSync('username', Username)
          wx.setStorageSync('role', role)
          this.setData({
            userName: null,
            passWord: null
          })
          let token = JSON.stringify(res.data.token)
          wx.setStorageSync('token', token)
          wx.setStorageSync('hasShownBindPrompt', false);
          wx.switchTab({ url: '/pages/homework/homeworkSituation/homeworkSituation' })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000 //持续的时间
          })
          this.setData({ attention: res.data.msg })
        }
      }
    } catch (err) {
      console.error('bindLogin 出错:', err);
      wx.showToast({ title: '登录失败，请稍后再试', icon: 'none' });
    }
  },

  goManualLogin() {
    this.setData({
      showBindDialog: false,
      useAutoLogin: false
    });
    wx.removeStorageSync('teacherToken');
    wx.removeStorageSync('username');
  },



  getUserProfile() {
    wx.navigateTo({
      url: '/pages/homework/serverweb/serverweb',
    })
  },
  changeExamNumber(e) {
    this.setData({ studentNum: e.detail.value })
  },
  changeUsername(e) {
    this.setData({ studentName: e.detail.value })
  },
  loginsubmit() {
    // let {examNumber,username} = this.data
    // console.info(examNumber)
    wx.setStorageSync('hasShownBindPrompt', false);

    wx.switchTab({ url: '/pages/homework/selecthomework/selecthomework' })
  },
  async loginsubmit() {
    if (this.data.role == 2) {
      let { studentNum, studentName } = this.data
      if (!studentNum) {
        this.setData({ attention: '准考证号不能为空' })
        return false
      }
      if (!studentName) {
        this.setData({ attention: '考生姓名不能为空' })
        return false
      }
      // this.setData({examNumber:null,username:null})
      this.setData({
        attention: ''
      })
      let that = this
      let options = {
        url: '/student/login',
        method: 'get',
        data: { studentNum: studentNum, studentName: studentName },
        header: { "content-type": "application/json;charset=UTF-8" }
      }
      let res = await http(options)
      if (res && res.data.code == 200) {
        let role = "student"
        wx.setStorageSync('role', role)
        this.setData({
          studentNum: null,
          studentName: null
        })
        let studentUserInfo = res.data.data
        let token = JSON.stringify(res.data.data)
        wx.setStorageSync('studentUserInfo', studentUserInfo);
        wx.setStorageSync('studentToken', token)
        wx.setStorageSync('hasShownBindPrompt', false);

        wx.switchTab({ url: '/pages/homework/selecthomework/selecthomework' })
      } else {
        this.setData({ attention: res.data.message })
      }
    } else {
      let { userName, passWord } = this.data
      if (!userName) {
        this.setData({ attention: '账号不能为空' })
        return false
      }
      if (!passWord) {
        this.setData({ attention: '密码不能为空' })
        return false
      }
      // this.setData({examNumber:null,username:null})
      this.setData({
        attention: ''
      })
      let that = this
      let options = {
        url: '/loginMini',
        method: 'post',
        data: { username: this.data.userName, password: this.data.passWord },
        header: { "content-type": "application/json;charset=UTF-8" }
      }
      let res = await httpLogin(options)
      if (res && res.data.code == 200) {
        let role = "teacher"
        wx.setStorageSync('username', this.data.userName)
        wx.setStorageSync('role', role)
        this.setData({
          userName: null,
          passWord: null
        })
        let token = JSON.stringify(res.data.token)
        wx.setStorageSync('token', token)
        wx.setStorageSync('hasShownBindPrompt', false);

        wx.switchTab({ url: '/pages/homework/homeworkSituation/homeworkSituation' })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000 //持续的时间
        })
        this.setData({ attention: res.data.msg })
      }
    }
  },
  onInputStudentNum(e) {
    this.setData({
      studentNum: e.detail.value
    });
    this.checkFormValid();
  },

  onInputStudentName(e) {
    this.setData({
      studentName: e.detail.value
    });
    this.checkFormValid();
  },
  onInputTeacherNum(e) {
    this.setData({
      userName: e.detail.value
    });
    this.checkFormTeacherValid();
  },

  onInputTeacherName(e) {
    this.setData({
      passWord: e.detail.value
    });
    this.checkFormTeacherValid();
  },
  // 检查表单是否有效
  checkFormValid() {
    const { studentNum, studentName } = this.data;
    const isValid = studentNum.trim() && studentName.trim();
    this.setData({
      isFormValid: isValid
    });
  },
  checkFormTeacherValid() {
    const { userName, passWord } = this.data;
    const isValid = userName.trim() && passWord.trim();
    this.setData({
      isFormValid: isValid
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})